package instantHelper.Raceway;

import instantHelper.Models.ConnectingRequests;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.media.MediaRecorder;
import android.os.Environment;

public class AudioRecorder {

	public MediaRecorder mrec = new MediaRecorder();

	private static final String TAG = "AudioRecording";
	File audiofile;
	int audioCounter = 0;
	int requestCount;
	private String androidId;
	String path;

	// constructor
	public AudioRecorder(String androidId, int requestCount) {
		this.androidId = androidId;
		this.requestCount = requestCount;

	}

	private String sanitizePath(String path) {
		if (!path.startsWith("/")) {
			path = "/" + path;
		}
		if (!path.contains(".")) {
			path += ".3gp";
		}
		return Environment.getExternalStorageDirectory().getAbsolutePath()
				+ path;
	}

	protected void recordAndSendAudio() throws IOException,
			InterruptedException {
		while (audioCounter < 5) {
			String audioPath = startRecording();
			audioCounter++;
			Thread.sleep(5000);
			stopRecording();
			sendRecordToCenterApp(audioPath);
		}
		mrec.release();
	}

	private void sendRecordToCenterApp(String audioPath) {
		String url = InstantHelperConstant.CentralAppURL
				+ "/androidhelprequest/newAudio";
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(7);
		nameValuePairs.add(new BasicNameValuePair("audioPath", audioPath));
		nameValuePairs.add(new BasicNameValuePair("androidId", androidId));
		nameValuePairs.add(new BasicNameValuePair("requestCount", Integer
				.toString(requestCount)));
		ConnectingRequests connectingRequests = new ConnectingRequests(url,
				nameValuePairs);
		connectingRequests.postData();

	}

	protected String startRecording() throws IOException {
		mrec.setAudioSource(MediaRecorder.AudioSource.MIC);
		mrec.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
		mrec.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
		path = "audio/audio_" + androidId + "_" + requestCount + "_"
				+ audioCounter + ".3gp";
		path = sanitizePath(path);
		// make sure the directory we plan to store the recording in exists
		File directory = new File(path).getParentFile();
		if (!directory.exists() && !directory.mkdirs()) {
			throw new IOException("Path to file could not be created.");
		}

		mrec.setOutputFile(path);

		mrec.prepare();
		mrec.start();
		return path;

	}

	protected void stopRecording() {
		mrec.stop();

	}

}